#!/usr/bin/perl
use strict;
use FindBin;


# ITER = number of random iterations
# RANGE = the range of identifiers
# MATCHIN = the range of identifiers which match (i.e. subset of RANGE)

#my ($ITER, $RANGE, $CLADES) = (100, 20, 5);
#my ($ITER, $RANGE, $CLADES) = (200000, 5000, 250);
#my ($ITER, $RANGE, $CLADES) = (20000000, 500000, 25000);
my ($ITER, $RANGE, $CLADES) = (2000, 50, 5);
die unless $RANGE > $CLADES;


my %id_to_clade;
print STDERR "\tGenerating test files\n";
{
	#
	#	Assign clade randomly
	#
	{
		open ID_TO_CLADE, ">$FindBin::Bin/clades.test";
		for (0..($RANGE-1))
		{
			my $clade =  "clade_" . int(rand($CLADES));
			print ID_TO_CLADE "id_$_\t$clade\n";
			$id_to_clade{$_} = $clade;
		}
	}

	#
	#	input file to filter
	#
	open RESULTS, ">$FindBin::Bin/results.test";
	print RESULTS "seq1\tseq2\n----\t----\n";

	open FILTERED, ">$FindBin::Bin/filtered.test";
	
	my $cnt_results = 0;
	print STDERR "\t[";
	for (0..$ITER)
	{
		
		print STDERR "." if ($_ % ($ITER / 50) == 0);
		++$cnt_results;
		my $id1 =  int(rand($RANGE));
		my $id2 =  int(rand($RANGE));
	
		die unless exists $id_to_clade{$id1};
		die unless exists $id_to_clade{$id2};
		my $line = "id_$id1\tid_$id2\tresult $id_to_clade{$id1}/$id_to_clade{$id2}\n";
		print RESULTS $line;
		if ($id_to_clade{$id1} eq $id_to_clade{$id2})
		{
			print FILTERED $line;
		}
	}
	print STDERR "]\n";
}

print STDERR "\tRunning seq_pairs_filter_by_clade\n";
system("seq_pairs_filter_by_clade -v --clades $FindBin::Bin/clades.test < $FindBin::Bin/results.test > ".
	   "$FindBin::Bin/filtered.try.test  ");
print STDERR "\tComparing results...\n";
{
	my @diff = `diff $FindBin::Bin/filtered.try.test $FindBin::Bin/filtered.test`;
	if (@diff != 0)
	{
		print STDERR "FAILED: filtered.try.test and filtered.test are not the same!\n";
		exit;
	}
}
print STDERR "\tCleaning up...\n";
unlink (glob("$FindBin::Bin/*.test"));
print STDERR "\n\tSUCCESS!!!\n\n";

